import { login, getUserInfo } from '@/api/sys'
import { JSEncrypt } from 'jsencrypt'
import { TOKEN, PUBLIC_KEY } from '../../constant'
import router, { resetRouter } from '../../router'
import { setTimeStamp } from '../../utils/auth'
import { getItem, removeAllItem, setItem } from '../../utils/storage'

export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    login(context, userInfo) {
      const { username, password } = userInfo
      var encrypt = new JSEncrypt()
      encrypt.setPublicKey(PUBLIC_KEY)
      const newPassword = encrypt.encrypt(password)
      return new Promise((resolve, reject) => {
        login({
          username,
          password: newPassword //md5(password)
        })
          .then((data) => {
            this.commit('user/setToken', data.accessToken)
            //保存登录时间
            setTimeStamp()
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    async getUserInfo(context) {
      const res = await getUserInfo()
      this.commit('user/setUserInfo', res)
      return res
    },

    async logout() {
      // await logout()
      resetRouter()

      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      removeAllItem()
      router.push('/login')
    }
  }
}
